/**
 */
package com.dingpeikeji.quickdeer.core.modules.realsche.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.bus.entity.TCompBus;
import com.dingpeikeji.quickdeer.core.modules.bus.service.TCompBusService;
import com.dingpeikeji.quickdeer.core.modules.line.entity.TLine;
import com.dingpeikeji.quickdeer.core.modules.line.service.TLineService;
import com.dingpeikeji.quickdeer.core.modules.orders.entity.TOrders;
import com.dingpeikeji.quickdeer.core.modules.orders.service.TOrdersService;
import com.dingpeikeji.quickdeer.core.modules.realsche.entity.TRealsche;
import com.dingpeikeji.quickdeer.core.modules.realsche.service.TRealscheService;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.modules.rentproduct.entity.TCargotype;
import com.dingpeikeji.quickdeer.modules.rentproduct.service.TCargotypeService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 实际班次Controller
 * 
 * @author Zhaoy
 * @version 2016-06-12
 */
@Controller
@RequestMapping(value = "${adminPath}/realsche/tRealsche")
public class TRealscheController extends BaseController {

	@Autowired
	private TRealscheService tRealscheService;
	@Autowired
	private TSitedtlService tSitedtlservice;
	@Autowired
	private TLineService tLineService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private TCompBusService compBusService;
	@Autowired
	private TCargotypeService tCargotypeService;
	@Autowired
	private TOrdersService tOrdersService;


	@ModelAttribute
	public TRealsche get(@RequestParam(required = false) String id) {
		TRealsche entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = tRealscheService.get(id);
		}
		if (entity == null) {
			entity = new TRealsche();
		}
		return entity;
	}
	
	
	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = "alllist")
	public String alllist(TRealsche tRealsche, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (tRealsche.getOfficeid() == null)
			tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());

		if (tRealsche.getDepartdate() == null)
			tRealsche.setDepartdate(new Date());
					
		model.addAttribute("tRealsche", tRealsche);
		model.addAttribute("today", DateUtils.getDate("yyyy-MM-dd")); // 当天日期字符串

		Page<TRealsche> page = tRealscheService.findPage(new Page<TRealsche>(request, response), tRealsche);
		model.addAttribute("page", page);
		return "modules/realsche/tRealscheAllList";
	}

	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = { "list", "" })
	public String list(TRealsche tRealsche, HttpServletRequest request, HttpServletResponse response, Model model) {
		//实际班次调度只查询临时班次
		tRealsche.setSchekind(TRealsche.SCHE_KIND_TEMP);
		
		if (tRealsche.getOfficeid() == null)
			tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());

		if (tRealsche.getDepartdate() == null)
			tRealsche.setDepartdate(new Date());
					
		model.addAttribute("tRealsche", tRealsche);
		model.addAttribute("today", DateUtils.getDate("yyyy-MM-dd")); // 当天日期字符串

		Page<TRealsche> page = tRealscheService.findPage(new Page<TRealsche>(request, response), tRealsche);
		model.addAttribute("page", page);
		return "modules/realsche/tRealscheList";
	}
	
	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = { "rentlist" })
	public String rentlist(TRealsche tRealsche, HttpServletRequest request, HttpServletResponse response, Model model) {
		//整车调度调度只查询整车班次,未调度列表
		tRealsche.setSchekind(TRealsche.SCHE_KIND_CANBERENT);
		tRealsche.setDispstatus(TRealsche.DISP_ST_NOTPATCH);
		
		//取订单状态为已支付的订单
		TOrders tmporder = new TOrders();
		tmporder.setOrderstatus(TOrders.STATUS_PAY);
		tRealsche.setOrder(tmporder);
				
		//只查询本公司
		if (tRealsche.getOfficeid() == null)
			tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());
					
		model.addAttribute("tRealsche", tRealsche);
		model.addAttribute("today", DateUtils.getDate("yyyy-MM-dd")); // 当天日期字符串

		Page<TRealsche> page = tRealscheService.findPage(new Page<TRealsche>(request, response), tRealsche);
		model.addAttribute("page", page);
		return "modules/realsche/tRealscheRentList";
	}
	
	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = { "dispatchedlist" })
	public String dispatchedlist(TRealsche tRealsche, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只查询整车班次,已调度列表
		tRealsche.setSchekind(TRealsche.SCHE_KIND_CANBERENT);
		tRealsche.setDispstatus(TRealsche.DISP_ST_PATCHED);
		
		//只查询本公司
		if (tRealsche.getOfficeid() == null)
			tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());
					
		model.addAttribute("tRealsche", tRealsche);
		model.addAttribute("today", DateUtils.getDate("yyyy-MM-dd")); // 当天日期字符串
		
		ArrayList<TCargotype> cartypelist = (ArrayList<TCargotype>) tCargotypeService.findalltypes();
		model.addAttribute("tCargotypeList", cartypelist);

		Page<TRealsche> page = tRealscheService.findPage(new Page<TRealsche>(request, response), tRealsche);
		model.addAttribute("page", page);
		
		return "modules/realsche/tRealscheDispatchedList";
	}


	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = "form")
	public String form(TRealsche tRealsche, String updateorview, Model model) {
		int i = 0;
		
		Date tomorrow = new Date();
		Calendar ca = new GregorianCalendar();
		ca.setTime(tomorrow);
		ca.add(ca.DATE, 1);
		tomorrow = ca.getTime();
		//初值
		if (tRealsche.getDepartdate() == null)
			tRealsche.setDepartdate(tomorrow);
		
		model.addAttribute("tomorrow", DateUtils.formatDate(tomorrow, "yyyy-MM-dd"));
		model.addAttribute("tRealsche", tRealsche);
		// 将上客点 车辆 信息通过json传递给页面
		model.addAttribute("board", tRealsche.gettRealscheBoardList());
		model.addAttribute("boardnum", tRealsche.gettRealscheBoardList().size());
		model.addAttribute("off", tRealsche.gettRealscheOffList());
		model.addAttribute("offnum", tRealsche.gettRealscheOffList().size());
		model.addAttribute("veh", tRealsche.gettRealscheVehiList().size());
		
		// 查询站点
		model.addAttribute("tSitedList", tSitedtlservice.findListAll());
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);

		model.addAttribute("updateorview", updateorview);
		model.addAttribute("today", DateUtils.getDate("yyyy-MM-dd")); // 当天日期字符串

		return "modules/realsche/tRealscheForm";
	}
	
	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = "rentdispform")
	public String rentdispform(TRealsche tRealsche, Model model) {
		/*Double dueamount = tOrdersService.findDueaMount(tRealsche.getOrder().getOrderid());
		tRealsche.getOrder().setDueamount(dueamount.toString());*/
		
		model.addAttribute("tRealsche", tRealsche);
		// 将上客点 车辆 信息通过json传递给页面
		model.addAttribute("veh", tRealsche.gettRealscheVehiList().size());
		
		List<Map<String, Object>> mapList = Lists.newArrayList();
		TCompBus qryBus = new TCompBus();
		qryBus.setOffice( UserUtils.getUser().getOffice());
		
		//如果是整车产品，则需要限制车型,客户定制包车不需要
		if (tRealsche.getSchekind().equals(TRealsche.SCHE_KIND_RENT))
			qryBus.setCartype(tRealsche.getOrder().getCartype());
		
		qryBus.setBusstatus(TCompBus.ST_IN_USE);
		
		List<TCompBus> list = compBusService.findList(qryBus);
		for (int i = 0; i < list.size(); i++) {
			TCompBus e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("busid", e.getBusid());
			map.put("licenseno", e.getLicenseno());
			map.put("maindriver", e.getMaindriver());
			map.put("drvname", e.getDrvname());
			map.put("mobile", e.getMobile());
			mapList.add(map);
		}
		model.addAttribute("buslist", mapList);
		
		return "modules/realsche/tRealscheRentForm";
	}
	
	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = "rentdispView")
	public String rentdispView(TRealsche tRealsche, Model model) {
		/*Double dueamount = tOrdersService.findDueaMount(tRealsche.getOrder().getOrderid());
		tRealsche.getOrder().setDueamount(dueamount.toString());*/
		String offerMount = tRealscheService.findOfferMount(tRealsche.getRealscheid());
		tRealsche.setOffermount(offerMount);
		model.addAttribute("tRealsche", tRealsche);
		// 将上客点 车辆 信息通过json传递给页面
		model.addAttribute("veh", tRealsche.gettRealscheVehiList().size());
		
		List<Map<String, Object>> mapList = Lists.newArrayList();
		TCompBus qryBus = new TCompBus();
		qryBus.setOffice( UserUtils.getUser().getOffice());
		
		//如果是整车产品，则需要限制车型,客户定制包车不需要
		if (tRealsche.getSchekind().equals(TRealsche.SCHE_KIND_RENT))
			qryBus.setCartype(tRealsche.getOrder().getCartype());
				
		List<TCompBus> list = compBusService.findList(qryBus);
		for (int i = 0; i < list.size(); i++) {
			TCompBus e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("busid", e.getBusid());
			map.put("licenseno", e.getLicenseno());
			map.put("maindriver", e.getMaindriver());
			map.put("drvname", e.getDrvname());
			map.put("mobile", e.getMobile());
			mapList.add(map);
		}
		model.addAttribute("buslist", mapList);
		
		return "modules/realsche/tRealscheRentView";
	}

	@RequiresPermissions("realsche:tRealsche:view")
	@RequestMapping(value = "formView")
	public String formView(TRealsche tRealsche, Model model) {
		model.addAttribute("tRealsche", tRealsche);
		// 将上客点 车辆 信息通过json传递给页面
		JSONArray tRealscheBoardJson = new JSONArray();
		for (int i = 0; i < tRealsche.getTRealscheBoardList().size(); i++) {
			JSONObject jo = new JSONObject();
			jo.put("boardseqno", tRealsche.getTRealscheBoardList().get(i).getSeqno());
			jo.put("boardaddr", tRealsche.getTRealscheBoardList().get(i).getBoardaddr());
			jo.put("boardtime", tRealsche.getTRealscheBoardList().get(i).getBoardtime());
			jo.put("citycode", tRealsche.getTRealscheBoardList().get(i).getCitycode());
			jo.put("retailprice", tRealsche.getTRealscheBoardList().get(i).getRetailprice());
			jo.put("settleprice", tRealsche.getTRealscheBoardList().get(i).getSettleprice());
			tRealscheBoardJson.add(jo);
		}
		JSONArray tRealscheOffJson = new JSONArray();
		for (int i = 0; i < tRealsche.getTRealscheOffList().size(); i++) {
			JSONObject jo = new JSONObject();
			jo.put("offseqno", tRealsche.getTRealscheOffList().get(i).getSeqno());
			jo.put("offaddr", tRealsche.getTRealscheOffList().get(i).getOffaddr());
			jo.put("citycode", tRealsche.getTRealscheOffList().get(i).getCitycode());
			jo.put("gathertime", tRealsche.getTRealscheOffList().get(i).getGathertime());
			tRealscheOffJson.add(jo);
		}
		JSONArray tRealscheVehJson = new JSONArray();
		for (int i = 0; i < tRealsche.getTRealscheVehiList().size(); i++) {
			JSONObject jo = new JSONObject();
			JSONObject officejson = new JSONObject();
			officejson.put("id", tRealsche.getTRealscheVehiList().get(i).getOffice().getId());
			officejson.put("name", tRealsche.getTRealscheVehiList().get(i).getOffice().getName());
			jo.put("office", officejson);
			jo.put("licno", tRealsche.getTRealscheVehiList().get(i).getLicno());
			jo.put("maindriver", tRealsche.getTRealscheVehiList().get(i).getMaindriver());
			jo.put("vehiclename", tRealsche.getTRealscheVehiList().get(i).getVehiclename());
			jo.put("seats", tRealsche.getTRealscheVehiList().get(i).getSeats());

			tRealscheVehJson.add(jo);
		}
		// 上下客店 巴士子类
		model.addAttribute("tRealscheBoardJson", tRealscheBoardJson);
		model.addAttribute("tRealscheOffJson", tRealscheOffJson);
		model.addAttribute("tRealscheVehJsson", tRealscheVehJson);
		// 查询线路
		TLine tLine = new TLine();
		model.addAttribute("tlinelist", tLineService.findList(tLine));
		// 查询站点

		model.addAttribute("tSitedList", tSitedtlservice.findListAll());
		// 查出所有客运公司
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Office qryOffice = new Office();
		qryOffice.setFlatType(Office.FLAT_TYPE_BUS);
		List<Office> list = officeService.findListByTerm(qryOffice);
		for (int i = 0; i < list.size(); i++) {
			Office e = list.get(i);
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", e.getId());
			map.put("pId", e.getParentId());
			map.put("pIds", e.getParentIds());
			map.put("name", e.getName());
			mapList.add(map);
		}
		model.addAttribute("officelist", mapList);
		return "modules/realsche/tRealscheFormView";
	}

	@RequiresPermissions("realsche:tRealsche:edit")
	@RequestMapping(value = "save")
	public String save(TRealsche tRealsche, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		// 后台验证
		if (!beanValidator(model, tRealsche)) {
			return form(tRealsche, "", model);
		}
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmm");
		Date date = new Date();
		tRealsche.setSchecode(formatter.format(date));
		tRealsche.setCreateby(UserUtils.getUser().getId());
		tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());
		tRealsche.setCompanyid(UserUtils.getUser().getCompany().getId());
		tRealscheService.save(tRealsche);
		addMessage(redirectAttributes, "保存实际班次成功");
		return "redirect:" + Global.getAdminPath() + "/realsche/tRealsche/?repage";
	}
	
	@RequiresPermissions("realsche:tRealsche:edit")
	@RequestMapping(value = "dispatchrent")
	public String dispatchrent(TRealsche tRealsche, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		String orderid = tRealsche.getOrder().getOrderid();
		//相同shareid下的所有订单统一调度
		String shareid = tRealsche.getOrder().getShareid();
		List<TOrders> orderList = tOrdersService.getOrderByShareId(shareid);
		if (orderList!=null&&orderList.size()>0) {
			for (TOrders tOrders : orderList) {
				tOrdersService.updateOfferMount(tOrders.getOrderid(),tRealsche.getOffermount());
				tRealsche.setCreateby(UserUtils.getUser().getId());
				tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());
				tRealsche.setCompanyid(UserUtils.getUser().getCompany().getId());
				tRealsche.setDispstatus(TRealsche.DISP_ST_PATCHED);
				tRealscheService.dispatch(tRealsche);
			}
		}else{
			tOrdersService.updateOfferMount(orderid,tRealsche.getOffermount());
			tRealsche.setCreateby(UserUtils.getUser().getId());
			tRealsche.setOfficeid(UserUtils.getUser().getOffice().getId());
			tRealsche.setCompanyid(UserUtils.getUser().getCompany().getId());
			tRealsche.setDispstatus(TRealsche.DISP_ST_PATCHED);
			tRealscheService.dispatch(tRealsche);
		}
		addMessage(redirectAttributes, "保存实际班次成功");
		//return "redirect:" + Global.getAdminPath() + "/realsche/tRealsche/rentlist?repage";
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/busOrderList?repage";
	}

	@RequiresPermissions("realsche:tRealsche:edit")
	@RequestMapping(value = "delete")
	public String delete(TRealsche tRealsche, RedirectAttributes redirectAttributes) {
		tRealscheService.delete(tRealsche);
		addMessage(redirectAttributes, "删除实际班次成功");
		//return "redirect:" + Global.getAdminPath() + "/realsche/tRealsche/?repage";
		return "redirect:" + Global.getAdminPath() + "/orders/tOrders/busOrderList?repage";
	}

}
